import { action, observable } from 'mobx';

import { pinyin } from 'pinyin-pro';
import Base from './base';
import isSuccess from '../utils/error';
import contactsServer from '../services/contacts';
import { netCheckFn } from '../utils/netCheck';

const {
    getList, searchContact, applyList, addContact, passContact, deleteContact, applyCount, setHasViewed
} = contactsServer;

export default class ContactsState extends Base {

    @observable contacts = [];
    @observable sortedContacts = [];
    @observable hasNew = false;
    @observable friends = [];
    @observable detailData = {};
    @observable loaded =false;

    contactsIdObj = {};

    @action.bound
    async getList(params) {
        this.contactsIdObj = {};
        this.loaded = false;
        // const res = await getList(params);
        let res = await netCheckFn('contactsList',async ()=>{
            const res = await getList(params);
            return res;
        });
        if (isSuccess(res) && res.data) {
            // console.log('---ContactsState getList---', res);
            this.contacts = res.data;

            // 收集联系人的userid，判断是否已经添加该联系人
            const obj = {};
            res.data.forEach(c => {
                obj[c.userid] = c.userid;
            });
            this.contactsIdObj = obj;
            this.loaded = true;
        }
    }

    @action.bound
    async getSortList(params, callback) { // 获取联系人并且排序
        // const res = await getList(params);
        let res = await netCheckFn('contactsList',async ()=>{
            const res = await getList(params);
            return res;
        });
        if (isSuccess(res) && res.data && res.data.length) {
            const numList = [];
            const obj = {};
            const others = [];
            res.data.forEach(v => {
                const first = v.realname ? v.realname.slice(0, 1) : '123';
                if (/^[0-9]*$/.test(first)) {
                    numList.push(v);
                    // console.log('num', first);
                } else if (/^[A-Za-z]+$/.test(first)) { // 字母开头
                    const letter = first.toLocaleUpperCase();
                    obj[letter] ? obj[letter].push(v) : obj[letter] = [v];
                    // console.log('letter', first.toLocaleUpperCase());
                } else if (/^[\u4e00-\u9fa5],{0,}$/.test(first)) { // 汉字开头
                    const letter = pinyin(first)[0][0].slice(0, 1).toLocaleUpperCase();
                    obj[letter] ? obj[letter].push(v) : obj[letter] = [v];
                    // console.log('汉字', first, pinyin(first)[0][0].slice(0,1).toLocaleUpperCase());
                } else {
                    others.push(v);
                }
            });
            // obj转为数组，并且排序
            const letters = [];
            for (let k in obj) {
                letters.push({ letter: k, list: obj[k] });
            }
            const sortedLetters = letters.sort((a, b) => {
                return a.letter.localeCompare(b.letter);
            });
            if (numList.length) sortedLetters.push({ letter: '#', list: numList });
            if (others.length) sortedLetters.push({ letter: 'others', list: others });

            // console.log('--sortedLetters--', sortedLetters);
            callback && callback(sortedLetters);
            this.sortedContacts = sortedLetters;

        }
    }

    @action.bound
    async searchContact(searchkey) {
        // const res = await searchContact({ searchkey });
        let res = await netCheckFn('searchContact-' + searchkey,async ()=>{
            const res = await searchContact({ searchkey });
            return res;
        });
        if (isSuccess(res)) {
            // console.log('---ContactsState searchContact---', res);
            this.friends = res.data;
        }
    }

    @action.bound
    async getDetail(v) {
        this.detailData = { info: v, applyList: null };
    }

    @action.bound
    async applyList(needSetHasViewed) {
        // const res = await applyList();
        let res = await netCheckFn('contactsApplyList',async ()=>{
            const res = await applyList();
            return res;
        });
        if (isSuccess(res)) {
            // console.log('---ContactsState applyList---', res);
            this.detailData = { info: null, applyList: res.data };
            // 设置已读
            needSetHasViewed && setHasViewed();
        }
    }

    @action.bound
    async addContact(params, callback) {
        const res = await addContact(params);
        if (isSuccess(res)) {
            // console.log('---ContactsState addContact---', res);
            callback && callback();
        }
    }

    @action.bound
    async passContact(params, callback) {
        const res = await passContact(params);
        if (isSuccess(res)) {
            // console.log('---ContactsState passContact---', res);
            callback && callback();
            // 刷新列表
            this.applyList();
            this.getList();
            this.getSortList();

        }
    }

    @action.bound
    async deleteContact(params, callback) {
        const res = await deleteContact(params);
        if (isSuccess(res)) {
            // console.log('---ContactsState deleteContact---', res);
            callback && callback();
            // 如果删除的是当前查看详情的联系人
            const info = this.detailData.info;
            const id = params.recids[0];
            if (info && info.recid === id) {
                this.detailData = { info: null, applyList: null };
            }
            // 刷新列表
            this.getList();
            this.getSortList();
        }
    }

    @action.bound
    async applyCount() {
        const res = await applyCount();
        if (isSuccess(res)) {
            // console.log('---ContactsState applyCount---', res);
            this.hasNew = res.data > 0;
        }
    }

    @action.bound
    async setHasViewed() {
        setHasViewed();
    }
}
